Chapter 12 the relevant graphical marks are highlighted in every view:

library(ggplot2)
library(plotly)
library(MESS)

data("happiness")

plot = 
  ggplot(happiness, 
            aes(x=tax, y=happy, color=continent, size=population, 
                text = paste("country:", country))) + 
  geom_point(alpha = .8) + 
  scale_size_area(max_size = 30) + 
  geom_smooth(aes(linetype = continent, group = continent),
              method="lm", se= F, size = 1
              )

ggplotly(plot)
library(plotly)
library(sf)
library(albersusa)

us_laea <- usa_sf("laea")
us_laea = us_laea %>% mutate(density_2014 = pop_2014/census_area)

plot =  
ggplot(us_laea) + 
  geom_sf(aes(fill = log(density_2014), 
              text = paste(name, "had a density of", round(density_2014, 0))))

ggplotly(plot, tooltip = "text") %>%
  style(hoverlabel = list(bgcolor = "grey85"), hoveron = "fill")

## Highlight time series across graphs Adapted from https://github.com/ropensci/plotly/tree/master/demo

txhousing.sd <- highlight_key(txhousing, ~year)

plot =  ggplot(txhousing.sd, aes(month, median)) +
  geom_line(aes(group = year)) + 
  geom_smooth(data = txhousing, method = "gam") + 
  facet_wrap(~ city) +
  labs(title = "Click on a line to highlight a year")

ggplotly(plot, height = 800, width = 1600)
## Warning: Removed 616 rows containing non-finite values
## (stat_smooth).
#%>%
 # layout(title = "Click on a line to highlight a year")

12.1

Linked plots Adapted from https://plotly-book.cpsievert.me/linking-views-without-shiny.html

txhousing.sd <- highlight_key(txhousing, ~city, "Select a city")

base <- plot_ly(txhousing.sd, color = I("black"), height = 400) %>%
  group_by(city)

plot1 <- base %>%
  summarise(miss = sum(is.na(median))) %>%
  filter(miss > 0) %>%
  add_markers(x = ~miss, y = ~forcats::fct_reorder(city, miss), hoverinfo = "x+y") %>%
  layout(
    barmode = "overlay",
    xaxis = list(title = "Number of months missing"),
    yaxis = list(title = "")
  ) 

plot2 <- base %>%
  add_lines(x = ~date, y = ~median, alpha = 0.3) %>%
  layout(xaxis = list(title = ""))

subplot(plot1, plot2, titleX = TRUE, widths = c(0.3, 0.7)) %>% 
  hide_legend() %>%
  highlight(dynamic = TRUE, selectize = TRUE)
## Adding more colors to the selection color palette.
## Setting the `off` event (i.e., 'plotly_doubleclick') to match the `on` event (i.e., 'plotly_click'). You can change this default via the `highlight()` function.
## Highlight data and fits
mpg.sd <- mpg
  #SharedData$new(mpg)
plot <- ggplot(mpg.sd, aes(displ, hwy, colour = class)) +
  geom_point() +
  geom_smooth(se = FALSE, method = "lm")

ggplotly(plot) %>% highlight("plotly_hover")

12.2 Time series scatterplot animation

ids and frame specify the data elements for the animation and slider

library(gapminder)

data(gapminder)

plot = 
ggplot(gapminder, aes(gdpPercap/1000, lifeExp, color = continent)) +
  geom_point(aes(size = pop, frame = year, ids = country)) +
  scale_x_log10()

ggplotly(plot)